package com.lgy.controller;

import com.lgy.beans.ProductCategory;
import com.lgy.exception.SellException;
import com.lgy.form.CategoryForm;
import com.lgy.service.ProductCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("seller/category")
public class SellCategoryController extends BaseController {

    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * 类目列表
     * @param map
     * @return
     * @throws SellException
     */
    @GetMapping("/list")
    public ModelAndView list(Map<String, Object> map) throws SellException {
        List<ProductCategory> categoryList = productCategoryService.findAll();
        map.put("categoryList", categoryList);
        return new ModelAndView("category/list", map);
    }

    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId", required = false) Integer categoryId,
                              Map<String, Object> map) throws SellException  {
        if (categoryId != null) {
            ProductCategory productCategory = productCategoryService.findOne(categoryId);
            map.put("productCategory", productCategory);
        }

        return new ModelAndView("category/index", map);
    }

    /**
     * 保存/更新
     * @param form
     * @return
     * @throws SellException
     */
    @PostMapping("/save")
    public ModelAndView save(@Valid CategoryForm form) throws SellException  {
        ProductCategory productCategory = new ProductCategory();
        if (form.getCategoryId() != null) {
            productCategory = productCategoryService.findOne(form.getCategoryId());
        }
        BeanUtils.copyProperties(form, productCategory);
        productCategoryService.save(productCategory);
        return new ModelAndView("common/success");
    }

}
